/**
 * Created by apple on 16/12/12.
 */
var _input_id = "";


window.onload = function () {
    if (storage_admin_id) {
        $('#dataTables-example').dataTable();
        $("#sideNav").click(function () {
            if ($(this).hasClass('closed')) {
                $('.navbar-side').animate({left: '0px'});
                $(this).removeClass('closed');
                $('#page-wrapper').animate({'margin-left': '260px'});

            }
            else {
                $(this).addClass('closed');
                $('.navbar-side').animate({left: '-260px'});
                $('#page-wrapper').animate({'margin-left': '0px'});
            }
        });
        $('.loading').hide();
    } else {
        window.location.href = "login.html"
    }
};


//上传图片
function setImagePreview(file) {
    $('.loading').show();
    _input_id = 0;
    if (file.files && file.files[0]) {
        var postfix = file.files[0].name.split('.').pop();
        if (postfix != "jpg" && postfix != "gif" && postfix != "png" && postfix != "jpeg") {
            $('.loading').hide();
            layer.msg("上传仅支持：jpg,gif,png,jpeg格式")
        } else {
            var reader = new FileReader();
            var ratio = "";
            var ext = '.' + file.files[0].name.split('.').pop();
            reader.onload = function (evt) {
                //加载图片获取图片真实宽度和高度
                var image = new Image();
                image.onload = function () {
                    //图片上传又拍云
                    var config = {
                        bucket: 'motorcycle',
                        expiration: parseInt((new Date().getTime() + 3600000) / 1000),
                        // 尽量不要使用直接传表单 API 的方式，以防泄露造成安全隐患
                        form_api_secret: '0jWegIsJu9xVxJMrgp4ydONAxok='
                    };
                    var instance = new Sand(config);
                    instance.upload("Image/" + parseInt((new Date().getTime() + 3600000) / 1000) + ext);

                };
                image.src = evt.target.result;
            };
            reader.readAsDataURL(file.files[0]);
        }
    } else {
        $('.loading').hide();
    }


}

document.addEventListener('uploaded', function (e) {
    for (var key in e.detail) {
        if (key === 'path') {
            var img_url = "http://motorcycle.b0.upaiyun.com" + e.detail[key];
            $('#img_show img').attr('src', img_url);
            $('.loading').hide();
        }

    }
});


var content = "";
var options = {
    'bucket': 'motorcycle',
    'save-key': '/Image/{filemd5}{.suffix}',
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400
};
// 上传请求的相关参数
var policy = window.btoa(JSON.stringify(options));
// 从 UPYUN 用户管理后台获取表单 API
var form_api_secret = '0jWegIsJu9xVxJMrgp4ydONAxok=';
// 计算签名
var signature = md5(policy + '&' + form_api_secret);

var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'pickfiles', // you can pass in id...
    container: document.getElementById('container'), // ... or DOM Element itself
    url: 'http://v0.api.upyun.com/' + options.bucket,
    filters: [
        {title: "Image files", extensions: "jpg,gif,png,jpeg"}
    ],
    multipart_params: {
        'Filename': '${filename}', // adding this to keep consistency across the runtimes
        'Content-Type': '',
        'policy': policy,
        'signature': signature
    },

    init: {
        PostInit: function () {
            document.getElementById('submit').onclick = function () {
                uploader.start();
                return false;
            };
        },

        FilesAdded: function (up, files) {
            plupload.each(files, function (file) {
                document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
            });
            if (files.length > 5) {
                layer.msg("最多只能上传5张图片!");
                uploader.init();
            } else {
                for (var i = 0; i < files.length; i++) {
                    if (files && files[i]) {
                        var img_num = $('#img_show_description').find('img').length;
                        if (img_num > 5) {
                            layer.msg("最多只能上传5张图片!")
                        } else if (img_num + files.length > 6) {
                            layer.msg("最多只能上传5张图片!")
                        } else {
                            if ($('#img_show_description').children('.add').find('img').attr('src') == "assets/img/add.jpg") {
                                $('#img_show_description').children('.add').html('');
                                $('#img_show_description').children('.add').append('<img src="assets/img/add2.jpeg" style="width:19%;margin-right: 1%;border: 1px solid black;float: left;" class="add2">');

                                $('#pickfiles').css('width', '18%');
                                $('.moxie-shim-html5').children('input').css('width', '18%');
                            }
                            var reader = new FileReader();
                            reader.readAsDataURL(files[i].getNative());
                            reader.onload = function (e) {
                                var image = new Image();
                                image.src = e.target.result;
                                image.onload = function () {
                                    var _img_num = $('#img_show_description').find('img').length;
                                    $('#img_show_description').children('.add').append('<img src="' + image.src + ' " style="width:19%;margin-right: 1%;border: 1px solid black;float: left;" id="QRcode_kids_0' + _img_num + '" class="QRcode_kids_0' + _img_num + '">');
                                    if (_img_num == 5) {
                                        $('.add2').remove()
                                        $('#pickfiles').remove();
                                        $('.moxie-shim-html5').remove();
                                    }
                                };
                            }
                        }
                    }
                }
            }

        },

        UploadProgress: function (up, file) {
            $('.loading').show();
            //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        },

        //单个文件上传完成
        FileUploaded: function (up, file, info) {
            var response = JSON.parse(info.response);
            document.getElementById('console').innerHTML += 'http://motorcycle.b0.upaiyun.com' + response.url + ",";

        },
        //所有文件上传完成
        UploadComplete: function (up, files) {
            content = $('#console').html();
            var _name = $('#theme_id_name').val();
            var _count = $('#theme_name_count').val();
            var _price = $('#theme_name_price').val();
            var _img_cover = $('#img_show img').attr('src');
            content = content.substring(0, content.length - 1);
            if (!_name) {
                layer.msg("请输入商品名称!", {time: 3000})
            } else if (!_count) {
                layer.msg("请输入商品余额!", {time: 3000})
            } else if (_count > 100000) {
                layer.msg("商品余额过大,请重新输入!", {time: 3000})
            } else if (!_price) {
                layer.msg("请输入商品单价!", {time: 3000})
            } else if (_price > 100000) {
                layer.msg("商品单价过大,请重新输入!", {time: 3000})
            } else if (!_img_cover || _img_cover == "assets/img/add.jpg") {
                layer.msg("请上传商品简图!", {time: 3000})
            } else if (!content) {
                layer.msg("请上传商品描述图!", {time: 3000})
            } else {
                $('.loading').hide();
                $.post("http://118.178.59.93:8080/Motocycle/api/v1/goods", {
                    good_name: _name,
                    remain_count: _count,
                    price: _price,
                    cover: _img_cover,
                    good_description: content
                }, function (data) {
                    try {
                        var obj = JSON.parse(data);
                        if (obj.code == 0) {
                            $('.loading').hide();
                            layer.msg("上传成功!");
                            setTimeout(function () {
                                location.reload();
                            }, 3000)
                        }
                    } catch (e) {
                        layer.msg(data.msg, {time: 3000});
                    }

                })
            }
        },
        Error: function (up, err) {
            layer.msg("服务器跑火星啦~~~待会儿再来吧~~~")
            //document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
        }
    }
});

uploader.init();